<template>
  <PageWrapper title="BI报表">
    <BasicForm @register="registerForm" :actionColOptions="{ span: 24 }" @submit="handleSubmit" />
    <div style="margin-top: 20px; margin-bottom: 20px;">
        <h3>图表</h3>
        <Checkbox v-model:checked="showPie">
          饼状图
        </Checkbox>
        <Checkbox v-model:checked="showBar">
          柱状图
        </Checkbox>
        <Checkbox v-model:checked="showLine">
          折线图
        </Checkbox>
        <Pie v-if="showPie" :keyOptions="keyOptions" :queryResult="queryResult" />
        <Bar v-if="showBar" :keyOptions="keyOptions" :queryResult="queryResult" />
        <Line v-if="showLine" :keyOptions="keyOptions" :queryResult="queryResult" />
    </div>
    <BasicTable @register="registerTable"  ref="tableRef" />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { ref } from 'vue';
  import { Checkbox } from 'ant-design-vue';
  import { PageWrapper } from '@/components/Page';
  import { BasicForm, useForm, FormSchema } from '@/components/Form';
  import { BasicTable, useTable } from '@/components/Table';
  import { executeSQL } from './api';
  import Pie from './charts/Pie.vue'
  import Bar from './charts/Bar.vue'
  import Line from './charts/Line.vue'

  const queryResult = ref([]);
  const showPie = ref(false);
  const showBar = ref(false);
  const showLine = ref(false);
  const keyOptions = ref([]);

  const formSchema: FormSchema[] = [
    {
      field: 'sql',
      label: 'SQL',
      component: 'InputTextArea',
      required: true,
      colProps: {
        span: 24,
      },
      componentProps: {
        placeholder: '请输入SQL语句，请谨慎输入',
        rows: 4,
      },
    },
  ];

  const [registerForm] = useForm({
    labelWidth: 60,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: true,
  });

  const [registerTable, { setColumns, setTableData }] = useTable({
    title: '查询结果',
    useSearchForm: false,
    showTableSetting: false,
    bordered: true,
    showIndexColumn: true,
  });

  async function handleSubmit(values) {
    const res = await executeSQL(values);
    let columns = [];
    let options = []
    if (res.length > 0) {
      for (const key in res[0]) {
        const column = {
          title: key,
          dataIndex: key,
        }
        columns.push(column);
        const option = {
          label: key,
          value: key,
        }
        options.push(option)
      }
    }
    queryResult.value = res;
    setColumns(columns);
    setTableData(res);
    keyOptions.value = options;
    showPie.value = false;
    showBar.value = false;
    showLine.value = false;
  }
</script>